package com.tongxin.van.frameworkcanary.http;


import android.text.TextUtils;

import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description:SmartSubscriber
 *
**/

public abstract class HttpResult implements Observer<ResponseBody> {


    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(ResponseBody responseBody) {
        try {
            String json = responseBody.string();
            JSONObject jsonObject = new JSONObject(json);
            if (Integer.parseInt(jsonObject.get("code").toString()) == 0) {//请求成功
                onSuccess(json);
            } else {//请求失败
                if (!TextUtils.isEmpty(jsonObject.getString("msg"))) {
                    onFail((String) jsonObject.get("msg"));
                } else {
                    onFail("请求失败，请稍后重试...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            onFail("请求失败，请稍后重试...");
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        onFail("请求失败，请稍后重试...");
    }

    @Override
    public void onComplete() {
    }


    protected abstract void onSuccess(String json);

    protected abstract void onFail(String message);

}
